/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package tickets;

import com.mysql.jdbc.Connection;
import com.mysql.jdbc.PreparedStatement;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.logging.Level;
import java.util.logging.Logger;

/**
 *
 * @author Nacho
 */
public class Conexion {
    private Connection conexion = null;
    public Conexion(String host, String user, String pass) {
         try {


            Class.forName("com.mysql.jdbc.Driver").newInstance();

            conexion = (Connection) DriverManager.getConnection("jdbc:mysql://"+host+":3306/itam_tickets", user, pass);

        } catch (Exception e) {
            System.out.println("No se conecto!");
            e.printStackTrace();
        }
    }
    
    public  ResultSet ejecutaSP(String sp){
        return execute("call "+sp);
    }
    public ResultSet execute(String e){
        ResultSet rs = null;
        try{
            Statement st;
            st = conexion.createStatement();
            st.execute(e);
            rs = st.getResultSet();
        }catch(Exception ex){
            System.out.println("Fallo un PS");
            ex.printStackTrace(); 
        }
        return rs;
    }
    
    public void close(){
        try{
        if (!conexion.isClosed()) {
                conexion.close();
        }
        }catch (Exception ex){
            System.out.println(ex);
        }  
    }
    public ResultSet ejecutaQuery(String q){
        ResultSet resultSet = null;
        try{
            PreparedStatement res=(PreparedStatement) conexion.prepareStatement(q);
            resultSet=res.executeQuery();
            
        }catch(Exception ex){
           System.out.println("Fallo el query");
            ex.printStackTrace(); 
        }
        return resultSet;
    }
    public static void main(String[] args) {
        System.out.println("Probando BaseDeDatos");
        String user = "jequgo";
        String pass = "Pupra7e6";
        String host = "mysql.itam.solucionw.com";
        Conexion cn = new Conexion(host,user,pass);
        ResultSet rs = cn.ejecutaQuery("SELECT * FROM CLIENTE");
        try {
            while(rs.next()){
                System.out.println(rs.getString(2));
            }
        } catch (SQLException ex) {
            ex.printStackTrace();
        }
    }
        
    
    
}
